package com.zp.common.pdf;

import com.zp.common.core.utils.StringUtils;
import com.zp.common.oss.file.FileUploadUtils;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 生成pdf
 * </p>
 *
 * @author zp
 * @since 2019/8/27
 */
public class HisReportPdf {

    /**
     * 模板所在位置路径
     */
    private final String templatePath;
    /**
     * 生成pdf保存路径
     */
    private final String exportFileName;
    private Map<String, Object> param;

    public HisReportPdf (String templatePath, String exportFileName) {
        this.templatePath = templatePath;
        if (StringUtils.isNotEmpty(templatePath)) {
            File file = new File(templatePath);
            if (!file.exists()) {
                throw new RuntimeException("文件模板不存在");
            }
            // 获取文件名称（不包含文件类型名）
            String name = file.getName().substring(0, file.getName().indexOf(".") - 1);
            // 输出路径传入的是“”的话默认拿文件所在路径
            if (StringUtils.isEmpty(exportFileName)) {
                exportFileName = file.getParent() + File.separator + name + ".pdf";
            }
        }
        this.exportFileName = exportFileName;
    }

    public static void main (String[] args, HttpServletRequest request, HttpServletResponse response) {
        HisReportPdf reportPdf = new HisReportPdf("D:\\static\\1098823\\3\\clinic_charge\\clinic_charge.jasper", "");
        // 参数
        Map<String, Object> map = new HashMap<>();
        List<test> list = new ArrayList<>();
        map.put("aaaa", "CsssT");
        map.put("vvvv", "CssswT");

        test aaa = new test();
        aaa.setAaa("22222a");
        aaa.setBbb("11111b");
        test aaa1 = new test();
        aaa1.setAaa("22222a");
        aaa1.setBbb("22222b");
        list.add(aaa1);
        list.add(aaa);
        map.put("lists", list);
        reportPdf.setParam(map);
        try {
            reportPdf.renderMergedOutputModel(map, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setParam (Map<String, Object> param) {
        this.param = param;
    }

    /**
     * pdf生成下载
     *
     * @param dataSource
     * @param request
     * @param response
     * @throws Exception
     */
    public synchronized void renderMergedOutputModel (Map<String, Object> dataSource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
//        DiagReportDataSource jrDataSource = new DiagReportDataSource(dataSource);
        JRDataSource jrDataSource = new JRBeanCollectionDataSource((Collection<?>) dataSource.get("lists"));
        // 创建打印 文件输入流
        FileInputStream fis = new FileInputStream(new File(templatePath));
        // 创建打印 文件输出流
        FileOutputStream fos = new FileOutputStream(new File(this.exportFileName));
        try {
            DefaultJasperReportsContext context = DefaultJasperReportsContext.getInstance();
            JRPropertiesUtil.getInstance(context).setProperty("net.sf.jasperreports.xpath.executer.factory",
                    "net.sf.jasperreports.engine.util.xml.JaxenXPathExecuterFactory");
            JasperPrint jasperPrint = JasperFillManager
                    .fillReport(fis, param, jrDataSource);

            JasperExportManager.exportReportToPdfStream(jasperPrint, fos);
            fos.flush();
            // 调用打印
            FileUploadUtils.printPdf(this.exportFileName, request, response);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }
}
